/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package top.dancun.easbaseinfo.oauth2;


import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.dancun.common.entity.UserEntity;
import top.dancun.common.entity.UserTokenEntity;
import top.dancun.common.utils.R;
import top.dancun.easbaseinfo.feign.ShiroFeign;
import top.dancun.easbaseinfo.utils.HttpContextUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 认证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private ShiroFeign shiroFeign;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String token = HttpContextUtils.getHttpServletRequest().getHeader("token");

        //用户权限列表
        R r =  shiroFeign.getUserPermissions(token);
        Set<String> permsSet=new HashSet<>();
        if(r.get("code").toString().equals("20000")){

            permsSet = new HashSet<String>((List<String>)r.get("permissions"));
        }


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        R r = shiroFeign.queryByToken(accessToken);
        UserTokenEntity tokenEntity=null;
        if(r.get("code").toString().equals("20000")){
            tokenEntity = JSON.parseObject(JSON.toJSONString(r.get("userTokenEntity")),UserTokenEntity.class) ;
        }

        //token失效
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        r = shiroFeign.queryUser(accessToken);
        UserEntity user = null;
        if(r.get("code").toString().equals("20000")){

            user =  JSON.parseObject(JSON.toJSONString(r.get("user")),UserEntity.class) ;
        }

        //账号锁定
        if(user.getStatus() == 0){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
        return info;
    }
}
